package com.ly.order.base;

import com.alibaba.fastjson.TypeReference;
import com.ass.rocketmq.base.AbstractTransactionListener;
import com.common.core.utils.SpringUtils;
import com.ly.order.service.OrderService;
import com.ly.order.service.TransactionLogService;
import com.domain.Order;
import lombok.Getter;
import lombok.extern.log4j.Log4j2;;
import org.springframework.stereotype.Component;

import java.util.function.BiConsumer;
import java.util.function.BiFunction;



@Log4j2
@Component
//这里是对应的业务 开发只关心这里
public class CusOrderTransactionListener extends AbstractTransactionListener<Order> {


    /**
     * 原因：注入不进来 因为ioc bean加载顺序的问题
     * 解释：CusOrderTransactionListener在orderService之前实例化了，orderService还没实例化所以为null
     * 解决办法：手动从ioc容器中拿出来
     * @Autowired private OrderService orderService;
     * @Autowired private TransactionLogService transactionLogService;
     */

    @Getter
    private final TypeReference<Order> model = new TypeReference<Order>(){};


    @Override
    protected BiConsumer<Order,String> doService() {
        OrderService bean = SpringUtils.getBean(OrderService.class);
        return (x,y)->bean.createOrder(x,y,doLocalTransaction());
    }

    //执行本地事务逻辑的设定 对应业务自己设置(这是必要的)
    @Override
    protected BiConsumer<Order,String> doLocalTransaction() {
        return (x,y)->{
            //随便自定义个事务 业务+事务id结合 如果两个都有true
            TransactionLogService transactionLogService = SpringUtils.getBean(TransactionLogService.class);
            transactionLogService.inertTransaction(y);
        };
    }

    @Override
    protected BiFunction<Order,String, Boolean> checkLocalTransaction() {
        return (x,y)->{
            //随便写一个自检事务的逻辑 业务+事务id结合 如果两个都有true
            OrderService orderService = SpringUtils.getBean(OrderService.class);
            Order order = orderService.oneById(x.getId());
            TransactionLogService transactionLogService = SpringUtils.getBean(TransactionLogService.class);
            int transactionId = transactionLogService.getTransactionId(y);
            if(order!=null && transactionId>0){
                return true;
            }else {
                return false;
            }
        };
    }
}
